package com.mogujie.tt.ui.activity;


import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;

import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;


import com.mogujie.tools.ScreenTools;
import com.mogujie.tt.DB.sp.ConfigurationSp;
import com.mogujie.tt.R;
import com.mogujie.tt.config.DBConstant;
import com.mogujie.tt.config.SysConstant;
import com.mogujie.tt.imservice.entity.RecentInfo;
import com.mogujie.tt.imservice.event.SessionEvent;
import com.mogujie.tt.imservice.manager.IMGroupManager;
import com.mogujie.tt.imservice.manager.IMLoginManager;
import com.mogujie.tt.imservice.manager.IMSessionManager;
import com.mogujie.tt.ui.base.QZBaseActivity;
import com.mogujie.tt.ui.widget.IMGroupAvatar;
import com.mogujie.tt.utils.DateUtil;
import com.mogujie.tt.utils.IMUIHelper;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.PauseOnScrollListener;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;


public class ChatRoomActivity extends QZBaseActivity {
    private ListView groupListView;
    private GroupChatAdapter groupAdapter;
    TextView tv_total;
    List<RecentInfo>  grouplist,alllist;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().registerSticky(this);
        LayoutInflater.from(this).inflate(R.layout.tt_activity_mychatroom, topContentView);
        showTopInformation("群聊");
        setTopRightAdd();
        groupListView = (ListView) findViewById(R.id.groupListView);

        alllist = IMSessionManager.instance().getRecentListInfo();//得到聊天的组

        grouplist = filterGroupChat(alllist);

       View headerView = LayoutInflater.from(this).inflate(R.layout.item_mychatroom_header, null);
       View footerView = LayoutInflater.from(this).inflate(R.layout.item_mychatroom_footer, null);
        tv_total = (TextView) footerView.findViewById(R.id.tv_total);
        tv_total.setText(String.valueOf(grouplist.size()) + "个群聊");

        try {
            groupAdapter = new GroupChatAdapter(ChatRoomActivity.this);
            groupAdapter.setData(grouplist);//设置数据
            groupListView.setOnItemClickListener(groupAdapter);
            groupListView.setOnItemLongClickListener(groupAdapter);
            groupListView.addHeaderView(headerView, null, false);
            groupListView.addFooterView(footerView, null, false);
            groupListView.setAdapter(groupAdapter);
            groupListView.setOnScrollListener(new PauseOnScrollListener(ImageLoader.getInstance(), true, true));

        }catch (Exception e){
            e.printStackTrace();
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        // grouplist = EMGroupManager.getInstance().getAllGroups();
        // groupAdapter = new MyChatRoomAdapter(this, 1, grouplist);
        // groupListView.setAdapter(groupAdapter);
        // groupAdapter.notifyDataSetChanged();
    }

    /**
     * 显示顶部信息
     */
    private void showTopInformation(String test){
        if(test == null){
            return;
        }
        setTopBarDisplay();

        setCenterText(test);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().unregister(this);
        }
        onDest();
    }

    public void onClickExit(View view){
        finish();
    }


    /**
     * 过滤群组
     * @param alllist
     * @return
     */
    private  List<RecentInfo> filterGroupChat( List<RecentInfo>  alllist){
        List<RecentInfo> filtergrouplist =new ArrayList<>();

               if (0  >= alllist.size()) {
                    return filtergrouplist;
                }
        for ( RecentInfo recentInfo:alllist) {
            if (recentInfo.getSessionType() == DBConstant.SESSION_TYPE_SINGLE) {

            } else if (recentInfo.getSessionType() == DBConstant.SESSION_TYPE_GROUP) {
                filtergrouplist.add(recentInfo);
            } else {

            }
        }

        return filtergrouplist;
    }


    /**
     * 群聊适配器
     */
    public  class GroupChatAdapter extends BaseAdapter implements
            AdapterView.OnItemClickListener,
            AdapterView.OnItemLongClickListener{

        private LayoutInflater mInflater = null;
        private List<RecentInfo> recentSessionList = new ArrayList<>();

        public GroupChatAdapter(Context context) {

            this.mInflater = LayoutInflater.from(context);
        }

        //设置组数据
        public void setData(List<RecentInfo> recentSessionList) {

            this.recentSessionList = recentSessionList;
           notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return recentSessionList.size();
        }

        @Override
        public Object getItem(int position) {
            if (position >= recentSessionList.size() || position < 0) {
                return null;
            }
            return recentSessionList.get(position);
        }

        @Override
        public long getItemId(int position){
            return position;
        }

        /**
         * 基本HOLDER
         */
        public  class ContactHolderBase{
            public TextView uname;
            public TextView lastContent;
            public TextView lastTime;
            public TextView msgCount;
            public ImageView noDisturb;
        }

        /**
         * 群组HOLDER
         */
        private  class GroupViewHolder extends ContactHolderBase{
            public IMGroupAvatar avatarLayout;
        }

        private View renderGroup(int position,View convertView, ViewGroup parent){
            RecentInfo recentInfo = recentSessionList.get(position);
            GroupViewHolder holder;
            if (null == convertView) {
                convertView = mInflater.inflate(R.layout.tt_item_chat_group, parent,false);
                holder = new GroupViewHolder();
                holder.avatarLayout = (IMGroupAvatar) convertView.findViewById(R.id.contact_portrait);
                holder.uname = (TextView) convertView.findViewById(R.id.shop_name);
                holder.lastContent = (TextView) convertView.findViewById(R.id.message_body);
                holder.lastTime = (TextView) convertView.findViewById(R.id.message_time);
                holder.msgCount = (TextView) convertView.findViewById(R.id.message_count_notify);
                holder.noDisturb = (ImageView)convertView.findViewById(R.id.message_time_no_disturb_view);
                convertView.setTag(holder);
            }else{
                holder = (GroupViewHolder)convertView.getTag();
            }

            if(recentInfo.isTop()){
                // todo   R.color.top_session_background
                convertView.setBackgroundColor(Color.parseColor("#f4f4f4f4"));
            }else{
                convertView.setBackgroundColor(Color.WHITE);
            }

            /**群屏蔽的设定*/
            if(recentInfo.isForbidden())
            {
                holder.noDisturb.setVisibility(View.VISIBLE);
            }
            else
            {
                holder.noDisturb.setVisibility(View.GONE);
            }

            handleGroupContact( holder,recentInfo);
            return convertView;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

              convertView =renderGroup(position,convertView,parent);

                return convertView;

        }


        private void handleGroupContact(GroupViewHolder groupViewHolder,RecentInfo recentInfo)
        {

            String avatarUrl = null;
            String userName = "";
            String lastContent = "";
            String lastTime = "";
            int unReadCount = 0;
            int sessionType = DBConstant.SESSION_TYPE_SINGLE;

            userName = recentInfo.getName();
            lastContent = recentInfo.getLatestMsgData();
            // todo 是不是每次都需要计算
            lastTime = DateUtil.getSessionTime(recentInfo.getUpdateTime());
            unReadCount = recentInfo.getUnReadCnt();
//        sessionType = recentInfo.getSessionType();
            // 设置未读消息计数 只有群组有的

            if (unReadCount > 0) {
                if(recentInfo.isForbidden())
                {
                    groupViewHolder.msgCount.setBackgroundResource(R.drawable.tt_message_botify_no_disturb);
                    groupViewHolder.msgCount.setVisibility(View.VISIBLE);
                    groupViewHolder.msgCount.setText("");
                    ((RelativeLayout.LayoutParams)groupViewHolder.msgCount.getLayoutParams()).leftMargin= ScreenTools.instance(this.mInflater.getContext()).dip2px(-7);
                    ((RelativeLayout.LayoutParams)groupViewHolder.msgCount.getLayoutParams()).topMargin=ScreenTools.instance(this.mInflater.getContext()).dip2px(6);
                    groupViewHolder.msgCount.getLayoutParams().width = ScreenTools.instance(this.mInflater.getContext()).dip2px(10);
                    groupViewHolder.msgCount.getLayoutParams().height = ScreenTools.instance(this.mInflater.getContext()).dip2px(10);

                }
                else
                {
                    groupViewHolder.msgCount.setBackgroundResource(R.drawable.tt_message_notify);
                    groupViewHolder.msgCount.setVisibility(View.VISIBLE);
                    ((RelativeLayout.LayoutParams)groupViewHolder.msgCount.getLayoutParams()).leftMargin=ScreenTools.instance(this.mInflater.getContext()).dip2px(-10);
                    ((RelativeLayout.LayoutParams)groupViewHolder.msgCount.getLayoutParams()).topMargin=ScreenTools.instance(this.mInflater.getContext()).dip2px(3);
                    groupViewHolder.msgCount.getLayoutParams().width = RelativeLayout.LayoutParams.WRAP_CONTENT;
                    groupViewHolder.msgCount.getLayoutParams().height = RelativeLayout.LayoutParams.WRAP_CONTENT;
                    groupViewHolder.msgCount.setPadding(ScreenTools.instance(this.mInflater.getContext()).dip2px(3),0,ScreenTools.instance(this.mInflater.getContext()).dip2px(3),0);

                    String strCountString=String.valueOf(unReadCount);
                    if (unReadCount>99) {
                        strCountString = "99+";
                    }
                    groupViewHolder.msgCount.setVisibility(View.VISIBLE);
                    groupViewHolder.msgCount.setText(strCountString);
                }

            } else {
                groupViewHolder.msgCount.setVisibility(View.GONE);
            }

            //头像设置
            setGroupAvatar(groupViewHolder, recentInfo.getAvatar());
            // 设置其它信息
            groupViewHolder.uname.setText(userName);
            groupViewHolder.lastContent.setText(lastContent);
            groupViewHolder.lastTime.setText(lastTime);

        }

        /**
         * 设置群头像
         * @param holder
         * @param avatarUrlList
         */
        private void setGroupAvatar(GroupViewHolder holder,List<String> avatarUrlList){

                if (null == avatarUrlList) {
                    return;
                }
                holder.avatarLayout.setAvatarUrlAppend(SysConstant.AVATAR_APPEND_32);
                holder.avatarLayout.setChildCorner(3);
                if (null != avatarUrlList) {
                    holder.avatarLayout.setAvatarUrls(new ArrayList<String>(avatarUrlList));
                }


        }

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            RecentInfo  recentInfo  = (RecentInfo) parent.getAdapter().getItem(position);
            if (recentInfo == null) {
                return;
            }
            IMUIHelper.openChatActivity(ChatRoomActivity.this, recentInfo.getSessionKey());
        }

        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            RecentInfo recentInfo =(RecentInfo) parent.getAdapter().getItem(position);
            if (recentInfo == null) {
                return false;
            }

                handleGroupItemLongClick(ChatRoomActivity.this,recentInfo);

            return true;
        }

        // 现在只有群组存在免打扰的
        private void handleGroupItemLongClick(final Context ctx, final RecentInfo recentInfo) {

            AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(ctx, android.R.style.Theme_Holo_Light_Dialog));
            builder.setTitle(recentInfo.getName());

            final boolean isTop = ConfigurationSp.instance(ctx, IMLoginManager.instance().getLoginId()).isTopSession(recentInfo.getSessionKey());
            final boolean isForbidden = recentInfo.isForbidden();
            int topMessageRes = isTop?R.string.cancel_top_message:R.string.top_message;
            int forbidMessageRes =isForbidden?R.string.cancel_forbid_group_message:R.string.forbid_group_message;

            String[] items = new String[]{ctx.getString(R.string.delete_session),ctx.getString(topMessageRes),ctx.getString(forbidMessageRes)};

            builder.setItems(items, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    switch (which) {
                        case 0 :
                            IMSessionManager.instance().reqRemoveSession(recentInfo);
                            break;
                        case 1:{
                            ConfigurationSp.instance(ctx, IMLoginManager.instance().getLoginId()).setSessionTop(recentInfo.getSessionKey(),!isTop);
                        }break;
                        case 2:{
                            // 底层成功会事件通知
                            int shieldType = isForbidden?DBConstant.GROUP_STATUS_ONLINE:DBConstant.GROUP_STATUS_SHIELD;
                            IMGroupManager.instance().reqShieldGroup(recentInfo.getPeerId(), shieldType);
                        }
                        break;
                    }
                }
            });
            AlertDialog alertDialog = builder.create();
            alertDialog.setCanceledOnTouchOutside(true);
            alertDialog.show();
        }
    }


    public void onEventMainThread(SessionEvent sessionEvent){

        switch (sessionEvent){
            case RECENT_SESSION_LIST_UPDATE:
            case RECENT_SESSION_LIST_SUCCESS:
            case SET_SESSION_TOP:
                UpdateGroupChat();
                break;
        }
    }

    private void  UpdateGroupChat(){
        alllist = IMSessionManager.instance().getRecentListInfo();//得到聊天的组
        grouplist = filterGroupChat(alllist);
        groupAdapter.setData(grouplist);//设置数据
        tv_total.setText(String.valueOf(grouplist.size()) + "个群聊");
    }
}
